import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/net/dio_api.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_button.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:url_launcher/url_launcher.dart';

//提示
class CasrHintDialog extends StatefulWidget {
  String? price;
  String? id;

  CasrHintDialog({
    Key? key,
    this.price,
    this.id,
  });

  @override
  State<StatefulWidget> createState() {
    return _CasrHintDialogState();
  }
}

class _CasrHintDialogState extends State<CasrHintDialog> {
  ConfigNameDetail? article;
  ConfigNameDetail? alArticle;
  StreamSubscription? testSubscription;

  @override
  void dispose() {
    super.dispose();
    try {
      testSubscription?.cancel();
    } catch (e) {}
  }

  @override
  void initState() {
    super.initState();
    getConfigNameDetailAli("alipay_is_open");
    getConfigNameDetail("wechatpay_is_open");
  }

  @override
  Widget build(BuildContext context) {
    final Widget content = Container(
      padding: EdgeInsets.only(top: 28, bottom: 34, left: 30, right: 30),
      width: Get.width - 40,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Center(
              child: Text(
            "￥${widget.price}",
            textAlign: TextAlign.center,
            style: TextStyle(
                fontSize: 40,
                fontFamily: "PingFangSC-Semibold",
                color: Color(0xFF222222)),
          )),
          SizedBox(
            height: 10,
          ),
          Center(
            child: Text(
              "您创作的作品我们将给您铸造在“HECO”公链，铸造过程中将消耗GAS费由您支付",
              style: TextStyle(
                  fontSize: 14,
                  color: Color(0xFF666666),
                  fontFamily: "PingFangSC-Semibold"),
            ),
          ),
          SizedBox(
            height: 30,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Container(
                width: 125,
                height: 40,
                child: MyButton(
                  onPressed: () {
                    Get.back();
                  },
                  text: "取消",
                  radius: 7,
                  fontSize: 16,
                  textColor: Global.kTheme.textPrimary4,
                  backgroundColor: Color(0xFFEFEFEF),
                ),
              ),
              Container(
                width: 125,
                height: 40,
                child: MyButton(
                  onPressed: () async {
                    int type = -1;
                    if (article?.value == "true" && alArticle?.value == "true") {
                      type = await showDialog(
                          context: context,
                          builder: (context) {
                            return new SimpleDialog(
                              title: Text("选择支付方式"),
                              children: [
                                new SimpleDialogOption(
                                  child: payItem(
                                    icon: "icon_wx",
                                    title: "微信",
                                    describe: "选择微信支付",
                                  ),
                                  onPressed: () {
                                    Navigator.of(context).pop(2);
                                  },
                                ),
                                new SimpleDialogOption(
                                  child: payItem(
                                    icon: "icon_zfb",
                                    title: "支付宝",
                                    describe: "选择支付宝支付",
                                  ),
                                  onPressed: () {
                                    Navigator.of(context).pop(1);
                                  },
                                ),
                              ],
                            );
                          });
                    } else {
                      if (article?.value == "true") {
                        type = 2;
                      } else if (alArticle?.value == "true") {
                        type = 1;
                      } else {
                        type = -1;
                      }
                    }
                    if ((alArticle?.value == "false" &&
                        article?.value == "false") || type == -1) {
                      EasyLoading.showToast("支付通道已关闭");
                      return;
                    }
                    EasyLoading.show(status: "加载中");
                    try {
                      if (type == 1) {
                        dynamic model;
                        model =
                            await ServiceRepository.specialCast3(id: widget.id!);
                        // toAlipay(model);
                        toWebAipay(model);
                      } else {
                        dynamic wxData = await ServiceRepository.specialWXCast(
                            id: widget.id!);
                        toWXPay(wxData);
                      }
                    } catch (e, s) {
                      EasyLoading.showToast(http.setError(e, s));
                    }
                  },
                  text: "立即支付",
                  radius: 7,
                  fontSize: 16,
                  textColor: Colors.white,
                  backgroundColor: Global.kTheme.colorBackground3,
                ),
              )
            ],
          )
        ],
      ),
    );

    final Widget body = MediaQuery.removeViewInsets(
      removeLeft: true,
      removeTop: true,
      removeRight: true,
      removeBottom: true,
      context: context,
      child: Center(
        child: content,
      ),
    );

    return Scaffold(
      backgroundColor: Colors.transparent, //透明类型
      body: body,
    );
  }


  void toWebAipay(dynamic model) async{
    if(model["body"]!=null && model["body"]["pay_url"]!=null){
      var _url= model["body"]["pay_url"];
      if (!await launch(_url)) throw 'Could not launch $_url';
      EasyLoading.dismiss();

      await showDialog(
          context: context,
          builder: (context) {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.all(30),
              child: SizedBox(
                width: 200,
                height: 220,
                child: Container(
                  padding: EdgeInsets.all(30),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius:
                      BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(Icons.offline_pin_rounded,size: 40,color: Colors.green,),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        "支付完成",
                        style: TextStyle(
                          fontSize: 18,
                          color: Global.kTheme.textPrimary6,
                          fontFamily: Global.mySemiboldFont,
                        ),
                      ),

                      SizedBox(
                        height: 10,
                      ),

                      SizedBox(
                        height: 10,
                      ),
                      MyButton(
                          minHeight: 40,
                          text: "完成",
                          fontSize: 17,
                          textColor: Global.kTheme.textPrimary5,
                          backgroundColor:
                          Global.kTheme.colorPrimary,
                          onPressed: () {
                            Navigator.of(Get.context!)
                              ..pop()
                              ..pop()
                              ..pop();
                          })
                    ],
                  ),
                ),
              ),
            );
          });
    }
  }

  void toAlipay(SpecialCastModel model) async {
    print("支付中----");
    //检测是否安装支付宝
    var result = await tobias.isAliPayInstalled();

    if (!result) {
      return EasyLoading.showToast('请安装支付宝');
    }

    if (result) {
      //去支付
      //orderInfo为后台返回的orderInfo
      var payResult = await tobias.aliPay(model.body ?? "");

      if (payResult['result'] != null) {
        if (payResult['resultStatus'].toString() == "9000") {
          EasyLoading.showToast('支付成功');
          Navigator.of(Get.context!)
            ..pop()
            ..pop();
        } else {
          EasyLoading.showToast('支付失败');
        }
      }
    }
  }

  void toWXPay(dynamic model) async {
    print("支付中----");
    await fluwx.registerWxApi(
        appId: "wx0f7153ca682343e0",
        universalLink: "https://www.com.example.limaiwl/app/");

    var result = await fluwx.isWeChatInstalled;
    if (!result) {
      return EasyLoading.showToast('请安装微信');
    }

    if (result) {
      //去支付
      //orderInfo为后台返回的orderInfo
      // 将下面这些参数替换成后台返回的即可
      var payRes = await fluwx.payWithWeChat(
        appId: model["body"]["appid"],
        partnerId: model["body"]["partnerid"],
        prepayId: model["body"]["prepayid"],
        packageValue: model["body"]["package"],
        nonceStr: model["body"]["noncestr"],
        timeStamp: model["body"]["timestamp"],
        sign: model["body"]["sign"],
      );

      // 支付回调
      // 一般情况下打开微信支付闪退，errCode为 -1 ，多半是包名、签名和在微信开放平台创建时的配置不一致。
      // 监听支付结果
      if(testSubscription!=null){
        testSubscription?.cancel();
      }
      testSubscription = fluwx.weChatResponseEventHandler.listen((event) async {
        print(event.errCode);
        // 支付成功
        if (event.errCode == 0) {
          EasyLoading.showToast('支付成功');
          Navigator.of(Get.context!)
            ..pop()
            ..pop();
        } else {
          // 关闭弹窗
          EasyLoading.showToast('支付失败');
        }
      });
    }
  }

  void getConfigNameDetail(String name) async {
    try {
      List list = await ServiceRepository.getConfigNameDetail(name);
      list.forEach((element) {
        if (element.name.toString().trim() == name) {
          article = element;
        }
      });
    } catch (e, s) {}
    setState(() {});
  }

  void getConfigNameDetailAli(String name) async {
    try {
      List list = await ServiceRepository.getConfigNameDetail(name);
      list.forEach((element) {
        if (element.name.toString().trim() == name) {
          alArticle = element;
        }
      });
    } catch (e, s) {}
    setState(() {});
  }

  Widget payItem({
    String? icon,
    String? title,
    String? describe,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 14),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          LoadImage(
            icon!,
            width: 28,
            height: 28,
          ),
          SizedBox(
            width: 10,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title!,
                style: TextStyle(
                    fontSize: 14,
                    color: Global.kTheme.textPrimary6,
                    fontFamily: Global.mySemiboldFont),
              ),
              Text(
                describe!,
                style: TextStyle(fontSize: 12, color: Color(0xFFA0A0A0)),
              ),
            ],
          ),
          Spacer(),
          // Icon(
          //   (isSelect ?? false)
          //       ? Icons.check_circle
          //       : Icons.radio_button_unchecked_rounded,
          //   size: 18,
          // ),
        ],
      ),
    );
  }
}
